#!/usr/bin/python3
import imaplib, email
import sys, getopt

"""
  The IMAP search parameter can reference

  https://tools.ietf.org/html/rfc3501#section-6.4.4
"""

imaplib._MAXLINE = 40000000

server = ""
user = ""
passwd = ""
pattern = ""
year = ""

def usage():
    print("del-mail.py <-u user> <-p password> <-m server> < <-f | -t | -c> | <-P>  pattern > [ -y year ]")


if __name__ == "__main__":

    opts, args = getopt.getopt(sys.argv[1:], "hm:u:p:f:t:c:P:y:", [])


    if len(opts) < 4:
        usage()
        exit()

    for o, a in opts:
        if o in ("-h"):
            usage()
            exit()
        elif o in ("-m"):
            server = a
        elif o in ("-u"):
            user = a
        elif o in ("-p"):
            passwd = a
        elif o in ("-f"):
            pattern = "(FROM \"" + a + "\")"
        elif o in ("-t"):
            pattern = "(TO \"" + a + "\")"
        elif o in ("-c"):
            pattern = "(CC \"" + a + "\")"
        elif o in ("-P"):
            pattern = a
        elif o in ("-y"):
            year = a

    print("Search pattern is : %s" % pattern)

    M = imaplib.IMAP4_SSL(server)

    #print M

    try:
        try:
            M.login(user, passwd)
        except Exception(e):
            print('Login error: %s' %e)
            M.close()
            sys.exit(1)
        print("Login: (%s) success !" % user)
        result, message = M.select("INBOX")

        result, msgnum = M.search(None, pattern)

        # total message deleted
        total_msg = 0
        num = 0
        if msgnum != ['']:
            total_msg = len(msgnum[0])
            print("Find %d message id match pattern %s" % (total_msg, pattern))
            #print(msgnum[0])

            msgset = msgnum[0].split()
            for n in msgset:
                # has year limit
                if year != "":
                    t, d = M.fetch(n, '(BODY[HEADER.FIELDS (DATE)])')
                    #print("message %s"% d[0][1].strip())
                    date = d[0][1].decode('utf-8')
                    if year not in date:
                        #t, d = M.fetch(n, '(BODY[HEADER.FIELDS (SUBJECT)])')
                        #print("Deleteing message, year: %s, id: %s, %s"% (year, n, d[0][1].strip()))
                        continue

                M.store(n, '+FLAGS', '\\Deleted')
                num = num + 1
                line = "Deleteing message id: {} ({} / {})".format(n, num, total_msg)
                print(line, "    \r",)
                sys.stdout.flush()
                if num % 200 == 0:
                    M.expunge()

        print("")
        print("total message delted: %d" % num)

    except Exception(e):
        print('Imap error: %s' %e)
        M.close()
    print("logout.")
    M.logout()
